<template>
  <!-- 新增/编辑商品弹框 -->
  <el-dialog
    class="add-store-dialog"
    :title="title"
    :visible.sync="addVisible"
    width="45%"
  >
    <div class="store-body">
      <el-form
        ref="storeFormRef"
        :rules="rules"
        :model="storeForm"
        label-width="120px"
      >
        <el-form-item prop="product_name" label="商品名称">
          <el-input v-model="storeForm.product_name"></el-input>
        </el-form-item>
        <el-form-item prop="category_id" label="商品分类">
          <el-select @change="onCategoryChange" v-model="storeForm.category_id" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.category_name"
              :value="item.category_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="product_description" label="商品描述">
          <el-input v-model="storeForm.product_description"></el-input>
        </el-form-item>
        <el-form-item prop="price" label="价格(元)">
          <el-input v-model="storeForm.price"></el-input>
        </el-form-item>
        <el-form-item prop="stock" label="库存(件)">
          <el-input v-model.number="storeForm.stock"></el-input>
        </el-form-item>
        <el-form-item prop="status" label="上下架">
          <el-switch
            style="display: block; margin-top: 10px"
            v-model="storeForm.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="上架"
            inactive-text="下架"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item>
        <el-form-item prop="pictures" label="图片内容" align="center">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="onImgChange"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog append-to-body :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { mapGetters } from "vuex";
import {
  getAllCategories,
  addProducts,
  updateProducts,
  uploadPictures,
} from "@/api/user";
import FileUploadEdit from "@/components/FileUploadEdit";
import { nanoid } from "nanoid";
export default {
  name: "AddDialog",
  components: { FileUploadEdit },
  props: {
    visible: {
      default: false,
      type: Boolean,
    },
    storeData: {
      type: Object,
      default: {},
    },
    title: {
      type: String,
      default: "新增商品",
    },
  },
  data() {
    return {
      //图片
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      //表单
      storeForm: {
        product_id: null,
        category_id: null,
        category_name: null,
        product_name:null,
        product_description: null,
        pictures: "",
        price: 0,
        stock: 0,
        status: 0,
      },
      fileList: [],
      options: [],
      rules: {
        product_name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        product_description: [
          {
            required: true,
            message: "请输入商品描述",
            trigger: "blur",
          },
        ],
        category_id: [
          {
            required: true,
            message: "请选择商品分类",
            trigger: "change",
          },
        ],
        price: [
          {
            required: true,
            message: "请选择输入价格",
            trigger: "blur",
          },
        ],
        price: [
          {
            required: true,
            message: "请选择输入库存",
            trigger: "stock",
          },
        ],
      },
    };
  },
  watch: {},
  created() {},
  async mounted() {
    await this.getAllCategories();
    if (this.title !== "新增商品") {
      this.handleEditInfo();
    }
  },
  computed: {
    ...mapGetters(["name", "token", "role"]),
    addVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
  },
  methods: {
    onCategoryChange(val){
   const findItem= this.options.find(item=>item.category_id===val)
   this.storeForm.category_name=findItem.category_name
    },
    async getAllCategories() {
      const res = await getAllCategories();
      this.options = res.data;
    },
    async onImgChange(file, fileList) {
      const imgUrl = await this.uploadImg(file.raw);
      imgUrl && (fileList[fileList.length - 1].url = imgUrl);
      this.fileList = fileList;
    },
    async uploadImg(file) {
      const formData = new FormData();
      formData.append("files", file);
      const res = await uploadPictures(formData);
      if (res?.status === 0 && res?.data?.pictures?.length > 0) {
        return res?.data?.pictures?.[0];
      } else {
        this.$message.error(res.message);
      }
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter((item) => item.name !== file.name);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },

    cancel() {
      this.$refs.storeFormRef.resetFields();
      this.addVisible = false;
    },
    handleEditInfo() {
      this.storeForm = this.storeData;
      const pictures =
        (this.storeForm?.pictures && JSON.parse(this.storeForm?.pictures)) ||
        [];
      this.fileList = pictures.map((item) => {
        return {
          name: nanoid(),
          url: item,
        };
      });
    },
    confirm() {
      this.$refs.storeFormRef.validate(async (valid) => {
        if (valid) {
          if (this.title === "新增商品") {
            if (!this.token)
              return this.$message.info("新增商品失败！请先登录后重试！");
            if (this.fileList.length <= 0)
              return this.$message.warning("请上传图片！");
            this.storeForm.pictures = JSON.stringify(
              this.fileList.map((item) => item.url)
            );
            const params = {
              category_id: this.storeForm?.category_id,
              category_name: this.storeForm?.category_name,
              product_name: this.storeForm?.product_name,
              product_description: this.storeForm?.product_description,
              price: +this.storeForm?.price,
              stock: +this.storeForm?.stock,
              status: +this.storeForm?.status,
              pictures: this.storeForm.pictures,
            };
           console.log(params);
            const res = await addProducts(params);
            if (res?.status === 0) {
              this.$message.success(res.message);
              this.$emit("confirm");
              this.addVisible = false;
            } else {
              this.$message.error(res.message);
            }
          } else {
            //编辑
            if (!this.storeForm?.product_id)
              return this.$message.warning("无id，请选择要编辑的信息!");
            this.storeForm.pictures = JSON.stringify(
              this.fileList.map((item) => item.url)
            );
            const params = {
              product_id: this.storeForm?.product_id,
              category_id: this.storeForm?.category_id,
              category_name: this.storeForm?.category_name,
              product_name: this.storeForm?.product_name,
              product_description: this.storeForm?.product_description,
              price: +this.storeForm?.price,
              stock: +this.storeForm?.stock,
              status: +this.storeForm?.status,
              pictures: this.storeForm.pictures,
            };
            const res = await updateProducts(params);
            if (res?.status === 0) {
              this.$message.success(res.message);
              this.$emit("confirm");
              this.addVisible = false;
            } else {
              this.$message.error(res.message);
            }
          }
        } else {
          console.log("错误提交！请重试！");
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-input {
  width: 220px;
}
.el-form {
  display: flex;
  flex-wrap: wrap;
}
.flex-per50 {
  width: 50%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-box {
  position: relative;
  .avatar-box-icon {
    position: absolute;
    top: -15px;
    right: -15px;
    font-size: 30px;
    color: red;
    cursor: pointer;
  }
}
</style>
